// Modules to control application life and create native browser window
const { app, BrowserWindow, Menu, ipcMain, dialog } = require('electron')
const path = require('path')
let mainWindow = null

function createWindow() {
  // require('./main/menu')

  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 1000,
    // 增加全量使用node.js，因为我们要使用node里的fs模块
    // enableRemoteModule 设置为true，否则不允许在渲染器上使用 remote
    webPreferences: {
      // sandbox: false, // 开启沙盒则preload脚本被禁用，所以得设为false
      preload: path.join(__dirname, 'preload.js')
      // nodeIntegration: true
      // enableRemoteModule: true
      // contextIsolation: false
    }
  })
  const menu = Menu.buildFromTemplate([
    {
      label: app.name,
      submenu: [
        {
          click: () => mainWindow.webContents.send('update-counter', 1),
          label: 'Increment'
        },
        {
          click: () => mainWindow.webContents.send('update-counter', -1),
          label: 'Decrement'
        }
      ]
    }
  ])

  // Menu.setApplicationMenu(menu)

  const dockMenu = Menu.buildFromTemplate([
    {
      label: 'New Window',
      click: function () {
        console.log('New Window')
      }
    },
    {
      label: 'New Window with Settings',
      submenu: [{ label: 'Basic' }, { label: 'Pro' }]
    },
    { label: 'New Command...' }
  ])
  // Menu.setApplicationMenu(dockMenu)

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')
  // mainWindow.loadURL(
  //   'https://mt.solar-grids.com/monitor/#/login'
  // )

  // Open the DevTools.
  mainWindow.webContents.openDevTools()
}

async function handleFileOpen() {
  const { canceled, filePaths } = await dialog.showOpenDialog()
  if (!canceled) {
    return filePaths[0]
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

  ipcMain.handle('ping', () => 'pong')
  ipcMain.on('set-title', (e, title) => {
    console.log(e, title)
    const webContents = e.sender
    const win = BrowserWindow.fromWebContents(webContents)
    win.setTitle(title)
  })
  ipcMain.handle('dialog:openFile', handleFileOpen)
  ipcMain.on('counter-value', (e, value) => {
    console.log(value)
  })

  // console.log(
  //   dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] })
  // )

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
  mainWindow.on('closed', () => {
    mainWindow = null
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

ipcMain.on('port', (event) => {
  const port = event.ports[0]

  port.on('message', (event) => {
    const data = event.data
  })

  port.start()
})
